var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs-extra');
var port = process.env.PORT || 3000;

server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

app.use(express.static(__dirname + '/public'));

// usernames which are currently connected to the chat
var usernames = {};
var participants = {};
var numUsers = 0;

var menu = fs.readJsonFileSync(__dirname + '/menu.json', {throws: true});

io.on('connection', function (socket) {
    var addedUser = false;

    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        socket.broadcast.emit('new message', {
            username: socket.username,
            message: data
        });
    });

    // when the client emits 'add user', this listens and executes
    socket.on('add user', function (username) {
        if (numUsers > 20) {
            socket.emit('login fail', {
                error: 1,
                message: '太多人了，坐不下了'
            });
            return;
        }
        if (usernames[username]) {
            socket.emit('login fail', {
                error: 2,
                message: '名字重复了！'
            });
            return;
        }
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        ++numUsers;
        addedUser = true;
        participants[username] = {};
        socket.emit('login', {
            numUsers: numUsers,
            menu: menu,
            participants: participants
        });
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('user joined', {
            username: socket.username,
            numUsers: numUsers
        });
    });

    socket.on('order dish', function(dishName) {
        var dishes = participants[socket.username] || {};
        if (dishes[dishName]) {
            dishes[dishName] = dishes[dishName] + 1;
        } else {
            dishes[dishName] = 1;
        }

        participants[socket.username] = dishes;

        socket.broadcast.emit('order dish', {
            username: socket.username,
            dishName: dishName
        });
    });

    socket.on('cancel dish', function(dishName, index) {
        var dishes = participants[socket.username] || {},
            num;
        if (dishes[dishName]) {
            num = dishes[dishName] - 1;
            if (num <= 0) {
                delete dishes[dishName];
            } else {
                dishes[dishName] = num;
            }
        }

        participants[socket.username] = dishes;
        socket.broadcast.emit('cancel dish', {
            username: socket.username,
            dishName: dishName,
            index: index
        });
    });

    // when the client emits 'typing', we broadcast it to others
    socket.on('typing', function () {
        socket.broadcast.emit('typing', {
            username: socket.username
        });
    });

    // when the client emits 'stop typing', we broadcast it to others
    socket.on('stop typing', function () {
        socket.broadcast.emit('stop typing', {
            username: socket.username
        });
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function () {
        // remove the username from global usernames list
        if (addedUser) {
            delete usernames[socket.username];
            delete participants[socket.username];

            --numUsers;

            // echo globally that this client has left
            socket.broadcast.emit('user left', {
                username: socket.username,
                numUsers: numUsers
            });
        }
    });
});